﻿using Common.Library.Db.RedisHelper;
using Newtonsoft.Json;
using SpiderCore.Loggers;
using StackExchange.Redis;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace SpiderCore.DB
{
    public class RedisDb : IDB
    {
        /// <summary>
        /// 初始化日志类型
        /// </summary>
        private readonly ISpiderLogger log = new SpiderMongoDBLog(typeof(RedisDb));
        IDatabase db;
        public RedisDb()
        {
            db = RedisClientHelp.Instance().GetRedisClient().GetDatabase();
        }

        /// <summary>
        /// 获取
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public T Get<T>(string key, object obj)
        {
            string json = db.StringGet(key);
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(json);
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="key"></param>
        /// <returns></returns>
        public bool Remove(string key)
        {
            DateTime dt1 = new DateTime().AddMilliseconds(10);//当前时间加10毫秒
            return db.StringSet(key, "", dt1.TimeOfDay);
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <param name="t"></param>
        /// <returns></returns>
        public bool Set<T>(string key, T t) where T : class
        {
            string json = JsonConvert.SerializeObject(t);
            return db.StringSet(key, json);
        }

        /// <summary>
        /// Redis消息队列
        /// </summary>
        /// <param name="key"></param>
        /// <param name="json"></param>
        public void ListLeftPush(string key, string json)
        {
            db.ListLeftPush(key, json);
        }

        /// <summary>
        /// 从消息队列中弹出一条数据
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="key"></param>
        /// <returns></returns>
        public T ListRightPop<T>(string key) where T : class
        {
            string json = db.ListRightPop(key);
            if (string.IsNullOrEmpty(json))
            {
                return default(T);
            }
            return JsonConvert.DeserializeObject<T>(json);
        }


    }
}
